#include "image.h"

#include <stdlib.h>
#include <string.h>

Image* image_new(struct Imageset* is, uint16_t w, uint16_t h, char* name)
{
	Image* img = calloc(1, sizeof(Image));
	img->name = strdup(name);
	img->w = w;
	img->h = h;
	img->is = is;
	img->data = calloc(w * h, 1);

	int i=0;
	for(i=0; i<(w*h); i++)
		img->data[i] = 0xff;

	return img;
}

void image_resize(Image* img, Rect r)
{
	// create new image
	uint8_t* data = calloc(r.w * r.h, 1);
	int i=0;
	for(i=0; i<(r.w*r.h); i++)
		data[i] = 0xff;

	// copy previous image
	int x1, x2, y1, y2;
	for(x1=r.x, x2=0; x2<r.w; x1++, x2++) 
		for(y1=r.y, y2=0; y2<r.h; y1++, y2++) 
		{
			//printf("(%d,%d) => (%d,%d)\n", x1, y1, x2, y2);
			uint8_t c;
			if(x1 < 0 || x1 >= img->w || y1 < 0 || y1 >= img->h)
				c = TRANSPARENT;
			else
				c = img->data[x1 + (y1 * img->w)];
			data[x2 + (y2 * r.w)] = c;
		}

	// free current image and instal the new one
	free(img->data);
	img->data = data;
	img->w = r.w;
	img->h = r.h;
}


void image_mirror(Image* img, Inversion inv)
{
	int x, y;
	if(inv == HORIZONTAL)
	{
		for(y=0; y<img->h; y++)
			for(x=0; x<(img->w/2); x++)
			{
				uint8_t s = img->data[x+(y*img->w)];
				img->data[x+(y*img->w)] = 
					img->data[(img->w-1-x)+(y*img->w)];
				img->data[(img->w-1-x)+(y*img->w)] = s;
			}
	}
	else if(inv == VERTICAL)
	{
		for(x=0; x<img->w; x++)
			for(y=0; y<(img->h/2); y++)
			{
				uint8_t s = img->data[x+(y*img->w)];
				img->data[x+(y*img->w)] = 
					img->data[x+((img->h-1-y)*img->w)];
				img->data[x+((img->h-1-y)*img->w)] = s;
			}
	}
}


void image_rotate(Image* img, Rotation rot)
{
	uint8_t* data = calloc(img->w * img->h, 1);
	uint16_t w = img->h;
	uint16_t h = img->w;

	int x, y;
	for(x=0; x<img->w; x++)
		for(y=0; y<img->h; y++)
			if(rot == CLOCKWISE)
				data[(w-y-1)+(x*w)] = P(img,x,y);
			else if(rot == ANTICLOCKWISE)
				data[y+((h-x-1)*w)] = P(img,x,y);
			else
				abort();
	free(img->data);
	img->data = data;
	img->w = w;
	img->h = h;
}


void image_free(Image* img)
{
	free(img->name);
	free(img->data);
	free(img);
}
